﻿using System;
using System.Collections.Generic;
using System.Linq;
using GCTrackableRace.Interfaces;
using GcTrackableRace.Entities;

namespace GcTrackableRace.ScoreCalculator.Rules
{
	public class AmountOfProvinceAndStateBordersCrossedRule: BaseRule, IRaceRule
	{
		public AmountOfProvinceAndStateBordersCrossedRule(string reportColumnName, string startDate, string endDate, string pointAllocation, 
			ILocationInfoLookup countryLookup)
			:base(reportColumnName, startDate, endDate, pointAllocation)
		{
			CountryLookup = countryLookup;
		}

		private ILocationInfoLookup CountryLookup { get; set; }
  
		protected override void SetRuleName()
		{
			RuleName = "Amount of province and state borders crossed rule";
		}

		public override void Process(ITrackable trackable, IEnumerable<ITrackableLog> trackableLogs)
		{
			var applicableLogs = (
				from log in trackableLogs
				where (
					(log.LogType == LogType.DroppedOff || log.LogType == LogType.Visited)
					&&
					log.Date >= StartDate &&
					log.Date <= EndDate
					)
				select log)
				.OrderBy(logs => logs.Date)
				.ThenBy(logs => logs.LogId)
				.ToList();

			var provincesAndStates = new List<string>();

			foreach (var log in applicableLogs)
			{
				var provinceOrState = CountryLookup.GetProvinceOrStateUsingCoords(log.Latitude, log.Longitude);

				if (!provincesAndStates.Any() || provincesAndStates.Last() != provinceOrState)
				{
					provincesAndStates.Add(provinceOrState);
				}
			}

			trackable.AddScore(new RuleScore(
				RuleName, 
				ReportColumnName,
				provincesAndStates.Count,
				(int)((provincesAndStates.Count > 1 ? provincesAndStates.Count - 1 : provincesAndStates.Count) * PointAllocation), 
				String.Join("|" , provincesAndStates).Trim('|')));
		}
	}
}
